from django.shortcuts import render
from django import http
# Create your views here.
from django.views import View
from .models import NewsChannel, Article
from django.core.paginator import Paginator, EmptyPage

class IndexView(View):
    def get(self,request,channel_id=1,page_num=1):
        '''新闻列表展示功能'''

        # 获取当前的频道对象
        try:
            channel = NewsChannel.objects.get(id=channel_id)
        except NewsChannel.DoesNotExist:
            return http.HttpResponseNotFound('未找到相应的NewsChannel')

        # 获取当前频道下的所有类别
        categories_id_list = [news_category.id for news_category in channel.newscategory_set.all() if news_category]

        # 查询当前频道下的所有文章
        articles =Article.objects.filter(category_id__in=categories_id_list).order_by('id')

        # 分⻚
        # 创建分⻚器：每⻚N条记录
        paginator = Paginator(articles, 3)
        # 获取每⻚新闻数据
        try:
            page_articles = paginator.page(page_num)
        except EmptyPage:
            # 如果page_num不正确，默认给⽤户404
            return http.HttpResponseNotFound('empty page')

        return render(request,'newsapp/index.html',{'articles':page_articles,'channel_id':channel_id})

class DetailView(View):
    def get(self,request,article_id):
        """新闻详情"""
        try:
            article = Article.objects.get(id=article_id)
        except Article.DoesNotExist:
            return http.HttpResponseNotFound('article_id不正确')

        return render(request,'newsapp/detail.html',{'article':article})